import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import { getResultsAction, updateResultsAction } from '@/store/action/search';
import { InfiniteScroll, Toast } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const { search } = useLocation();
  const res = new URLSearchParams(search);
  const q = res.get('q') as string;

  const dispatch = useDispatch();
  useEffect(() => {
    if (!q) {
      return Toast.show({ content: '参数为空' });
    }
    dispatch(getResultsAction(q));
  }, [dispatch, q]);

  useEffect(() => {
    return () => {
      dispatch({ type: 'search/saveResults', payload: {} });
    };
  }, [dispatch]);

  const { resultData } = useAppSelector((state) => state.search);
  const { results, page, total_count } = resultData;

  const loadMore = async () => {
    await dispatch(updateResultsAction(q, page + 1));
  };
  return (
    <div className={styles.root}>
      <NavBar fixed>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} itemData={item} />
        ))}
      </div>
      {!!results.length && (
        <InfiniteScroll loadMore={loadMore} hasMore={results.length < total_count} />
      )}
    </div>
  );
}
